/**
 * STM32 SM4封装层
 * ProvideClass似于STM32硬件加密的接口
 */

#include "stm32f4xx_sm4.h"
#include "sm4_impl.h"
#include <string.h>

/* SM4上下文（全局） */
static SM4_Impl_Context sm4_ctx;
static uint8_t sm4_initialized = 0;
static uint8_t sm4_key_set = 0;

/**
 * @brief InitializeSM4Module
 */
HAL_StatusTypeDef SM4_Init(void)
{
    sm4_initialized = 1;
    sm4_key_set = 0;
    memset(&sm4_ctx, 0, sizeof(SM4_Impl_Context));
    return HAL_OK;
}

/**
 * @brief SettingsSM4Key
 */
HAL_StatusTypeDef SM4_SetPassword(uint8_t* key, uint32_t key_len)
{
    if (!sm4_initialized) {
        return HAL_ERROR;
    }
    
    if (key == NULL || key_len != SM4_IMPL_KEY_SIZE) {
        return HAL_ERROR;
    }
    
    /* ExecuteKey扩展 */
    SM4_Impl_Init(&sm4_ctx, key);
    sm4_key_set = 1;
    
    return HAL_OK;
}

/**
 * @brief ExecuteSM4Command（加密Or解密）
 */
HAL_StatusTypeDef SM4_ProcessCommand(uint8_t cmd, 
                                     const uint8_t* input, 
                                     uint32_t input_len,
                                     uint8_t* output, 
                                     uint32_t* output_len)
{
    uint32_t i;
    
    if (!sm4_initialized || !sm4_key_set) {
        return HAL_ERROR;
    }
    
    if (input == NULL || output == NULL || output_len == NULL) {
        return HAL_ERROR;
    }
    
    /* CheckInput长度（必须Yes16的倍数） */
    if (input_len == 0 || (input_len % SM4_IMPL_BLOCK_SIZE) != 0) {
        return HAL_ERROR;
    }
    
    *output_len = input_len;
    
    /* 按块Process */
    for (i = 0; i < input_len; i += SM4_IMPL_BLOCK_SIZE) {
        if (cmd == SM4_CMD_ENCRYPT) {
            SM4_Impl_Encrypt_Block(&sm4_ctx, input + i, output + i);
        } else if (cmd == SM4_CMD_DECRYPT) {
            SM4_Impl_Decrypt_Block(&sm4_ctx, input + i, output + i);
        } else {
            return HAL_ERROR;
        }
    }
    
    return HAL_OK;
}
